<template>
  <a-modal
    :title="title"
    :width="1000"
    :visible="visible"
    @cancel="handleCancel"
    :footer="null"
  >
    <a-spin :spinning="confirmLoading">
      
      <!-- 采购单和退换货单基本信息 -->
      <a-card :bordered="false" title="基本信息" style="margin-bottom: 16px">
        <a-descriptions bordered :column="3" size="small">
          <a-descriptions-item label="采购单号">{{ purchaseOrder.purchaseNo }}</a-descriptions-item>
          <a-descriptions-item label="退换货单号">{{ currentReturnExchangeNo }}</a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="type == 2 ? 'red' : 'blue'">
              {{ type == 2 ? '退货单' : '换货单' }}
            </a-tag>
          </a-descriptions-item>
        </a-descriptions>
      </a-card>

      <!-- 退货/换货记录 -->
      <a-card :bordered="false" :title="type == 2 ? '退货记录' : '换货记录'">
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="returnExchangeList"
          :pagination="false"
          :scroll="{ x: 1300 }"
        >
          <!-- 物料类型列 -->
          <template slot="materialTypeSlot" slot-scope="text">
            <a-tag v-if="text" :color="
              text == '1' ? 'blue' : 
              text == '2' ? 'green' : 
              text == '3' ? 'orange' : 
              text == '4' ? 'purple' : 
              text == '5' ? 'red' : 
              text == '6' ? 'yellow' : ''"
            >
              {{ 
                text == '1' ? '型材' : 
                text == '2' ? '配件' : 
                text == '3' ? '辅件' : 
                text == '4' ? '其他' : 
                text == '5' ? '余料' : 
                text == '6' ? '半料' : '-'
              }}
            </a-tag>
          </template>

          <!-- 单价列 -->
          <template slot="unitPriceSlot" slot-scope="text">
            {{ text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00' }}
          </template>

          <!-- 金额列 -->
          <template slot="totalAmountSlot" slot-scope="text">
            {{ text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00' }}
          </template>

          <!-- 凭证列 -->
          <template slot="evidenceSlot" slot-scope="text">
            <div v-if="text" class="material-thumbnail-container">
              <img
                :src="getImageUrl(text)"
                class="material-thumbnail"
                alt="凭证"
                @click="handlePreviewImage(text)"
                @error="handleImageError"
              />
            </div>
            <span v-else>-</span>
          </template>

          <!-- 处理状态列 -->
          <template slot="statusSlot" slot-scope="text">
            <a-tag :color="text == 0 ? 'orange' : text == 1 ? 'blue' : text == 2 ? 'green' : text == 3 ? 'red' : ''">
              <j-dict-tag v-if="text !== null && text !== undefined" :value="text || ''" dictCode="return_exchange_status" />
              <span v-else>-</span>
            </a-tag>
          </template>
        </a-table>

        <!-- 汇总信息 -->
        <div style="text-align: right; margin-top: 12px;">
          <span style="margin-right: 12px;">总数量: <b>{{ totalQuantity }}</b></span>
          <span style="margin-right: 12px;">总金额: <b style="color: #f5222d; font-size: 16px;">
            ¥{{ totalAmount.toFixed(2) }}
          </b></span>
        </div>
      </a-card>
      
      <!-- 按钮区域 -->
      <div style="text-align: center; margin-top: 16px;">
        <a-button type="primary" icon="printer" @click="handlePrint" style="margin-right: 8px;">打印</a-button>
        <a-button type="primary" icon="file-pdf" @click="handleExportPDF" style="margin-right: 8px;">导出PDF</a-button>
        <a-button @click="handleCancel">关闭</a-button>
      </div>
    </a-spin>
    
    <!-- 图片预览模态框 -->
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img alt="凭证图片" style="width: 100%" :src="previewImage" />
    </a-modal>
  </a-modal>
</template>

<script>
import { getAction } from '@/api/manage'
import JDictTag from '@/components/dict/JDictTag'
import { getFileAccessHttpUrl } from '@/api/manage'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'

export default {
  name: 'ReturnExchangeDetailModal',
  components: {
    JDictTag
  },
  data() {
    return {
      title: '退换货单详情',
      visible: false,
      confirmLoading: false,
      type: 2, // 2-退货，3-换货
      purchaseOrder: {
        id: '',
        purchaseNo: '',
        supplier: '',
        totalAmount: 0,
        status: '',
        returnExchangeStatus: null,
        createBy: ''
      },
      currentReturnExchangeNo: '', // 当前退换货单号
      returnExchangeList: [],
      // 图片预览相关
      previewVisible: false,
      previewImage: '',
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '物料编码',
          align: "center",
          dataIndex: 'materialCode',
          width: 120
        },
        {
          title: '物料名称',
          align: "center",
          dataIndex: 'materialName',
          width: 150
        },
        {
          title: '物料类型',
          align: "center",
          dataIndex: 'materialType',
          width: 100,
          scopedSlots: { customRender: 'materialTypeSlot' }
        },
        {
          title: '规格型号',
          align: "center",
          dataIndex: 'specification',
          width: 120
        },
        {
          title: '供应商',
          align: "center",
          dataIndex: 'supplierName',
          width: 150
        },
        {
          title: '数量',
          align: "center",
          dataIndex: 'quantity',
          width: 100
        },
        {
          title: '单位',
          align: "center",
          dataIndex: 'unit',
          width: 80
        },
        {
          title: '单价',
          align: "center",
          dataIndex: 'unitPrice',
          width: 100,
          scopedSlots: { customRender: 'unitPriceSlot' }
        },
        {
          title: '金额',
          align: "center",
          dataIndex: 'totalAmount',
          width: 100,
          scopedSlots: { customRender: 'totalAmountSlot' }
        },
        {
          title: '原因',
          align: "center",
          dataIndex: 'reason',
          width: 200
        },
        {
          title: '凭证',
          align: "center",
          dataIndex: 'evidence',
          width: 100,
          scopedSlots: { customRender: 'evidenceSlot' }
        },
        {
          title: '处理状态',
          align: "center",
          dataIndex: 'status',
          width: 100,
          scopedSlots: { customRender: 'statusSlot' }
        }
      ],
      url: {
        detail: '/wms/purchase/queryById',
        returnExchangeList: '/wms/purchase/returnExchange/list'
      }
    }
  },
  computed: {
    totalQuantity() {
      return this.returnExchangeList.reduce((sum, item) => {
        return sum + parseFloat(item.quantity || 0);
      }, 0);
    },
    totalAmount() {
      return this.returnExchangeList.reduce((sum, item) => {
        return sum + parseFloat(item.totalAmount || 0);
      }, 0);
    }
  },
  methods: {
    show(purchaseOrderId, type) {
      this.visible = true;
      this.type = type; // 2-退货，3-换货
      this.title = type == 2 ? '退货单详情' : '换货单详情';
      this.loadData(purchaseOrderId);
    },
    loadData(purchaseOrderId) {
      this.confirmLoading = true;
      
      // 加载采购单基本信息
      getAction(this.url.detail, { id: purchaseOrderId }).then(res => {
        if (res.success && res.result) {
          this.purchaseOrder = res.result;
          
          // 加载退货/换货记录
          this.loadReturnExchangeList(purchaseOrderId);
        } else {
          this.$message.error(res.message || '加载采购单详情失败');
          this.confirmLoading = false;
        }
      }).catch(() => {
        this.confirmLoading = false;
      });
    },
    loadReturnExchangeList(purchaseOrderId) {
      getAction(this.url.returnExchangeList, { purchaseOrderId }).then(res => {
        if (res.success) {
          // 根据类型过滤记录
          const filteredList = (res.result || []).filter(item => item.type == (this.type - 1));
          this.returnExchangeList = filteredList;
          
          // 获取退换货单号
          if (filteredList.length > 0 && filteredList[0].returnExchangeNo) {
            this.currentReturnExchangeNo = filteredList[0].returnExchangeNo;
          } else {
            const prefix = this.type == 2 ? 'TH' : 'HH';
            this.currentReturnExchangeNo = `${this.purchaseOrder.purchaseNo}-${prefix}`;
          }
        } else {
          this.$message.error(res.message || '加载退换货记录失败');
        }
        this.confirmLoading = false;
      }).catch(() => {
        this.confirmLoading = false;
      });
    },
    getStatusColor(status) {
      // 状态颜色映射
      const statusColorMap = {
        '1': 'blue',    // 草稿
        '2': 'orange',  // 待审批
        '3': 'green',   // 已审批
        '4': 'cyan',    // 部分入库
        '5': 'purple',  // 已完成
        '6': 'red',      // 已取消
        '7': 'blue',      // 已到货
        '8': 'yellow'      // 部分到货
      }
      return statusColorMap[status] || 'default';
    },
    getReturnExchangeStatusColor(status) {
      // 退换货状态颜色映射
      const statusColorMap = {
        0: 'green', // 无需退换货
        1: 'orange', // 等待处理
        2: 'red', // 退货
        3: 'blue', // 换货
      }
      return statusColorMap[status] || 'default';
    },
    handleCancel() {
      this.visible = false;
      this.purchaseOrder = {
        id: '',
        purchaseNo: '',
        supplier: '',
        totalAmount: 0,
        status: '',
        returnExchangeStatus: null,
        createBy: ''
      };
      this.currentReturnExchangeNo = '';
      this.returnExchangeList = [];
    },
    handlePrint() {
      const printContent = document.querySelector('.ant-modal-body');
      const WinPrint = window.open('', '', 'width=800,height=900');
      
      WinPrint.document.write(`
        <html>
          <head>
            <title>${this.title}</title>
            <style>
              body {
                font-family: 'Microsoft YaHei', 'SimSun', sans-serif;
                padding: 20px;
              }
              table {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 20px;
              }
              table, th, td {
                border: 1px solid #ddd;
              }
              th, td {
                padding: 8px;
                text-align: center;
              }
              th {
                background-color: #f2f2f2;
              }
              .header {
                text-align: center;
                margin-bottom: 20px;
              }
              .info {
                margin-bottom: 20px;
              }
              .total {
                text-align: right;
                margin-top: 12px;
                font-weight: bold;
              }
            </style>
          </head>
          <body>
            <div class="header">
              <h2>${this.title}</h2>
            </div>
            <div class="info">
              <p><strong>采购单号：</strong>${this.purchaseOrder.purchaseNo}</p>
              <p><strong>退换货单号：</strong>${this.currentReturnExchangeNo}</p>
            </div>
            <table>
              <thead>
                <tr>
                  <th>序号</th>
                  <th>物料编码</th>
                  <th>物料名称</th>
                  <th>规格型号</th>
                  <th>数量</th>
                  <th>单位</th>
                  <th>单价</th>
                  <th>金额</th>
                  <th>原因</th>
                </tr>
              </thead>
              <tbody>
                ${this.returnExchangeList.map((item, index) => `
                  <tr>
                    <td>${index + 1}</td>
                    <td>${item.materialCode || '-'}</td>
                    <td>${item.materialName || '-'}</td>
                    <td>${item.specification || '-'}</td>
                    <td>${item.quantity || 0}</td>
                    <td>${item.unit || '-'}</td>
                    <td>¥${item.unitPrice ? parseFloat(item.unitPrice).toFixed(2) : '0.00'}</td>
                    <td>¥${item.totalAmount ? parseFloat(item.totalAmount).toFixed(2) : '0.00'}</td>
                    <td>${item.reason || '-'}</td>
                  </tr>
                `).join('')}
              </tbody>
            </table>
            <div class="total">
              <p>总数量: ${this.totalQuantity}</p>
              <p>总金额: ¥${this.totalAmount.toFixed(2)}</p>
            </div>
          </body>
        </html>
      `);
      
      WinPrint.document.close();
      WinPrint.focus();
      setTimeout(() => {
        WinPrint.print();
        WinPrint.close();
      }, 500);
    },
    handleExportPDF() {
      const fileName = `${this.type == 2 ? '退货单' : '换货单'}_${this.currentReturnExchangeNo}.pdf`;
      
      this.$message.loading('PDF生成中...', 0);
      
      // 使用和打印相同的内容格式
      const content = `
        <html>
          <head>
            <title>${this.title}</title>
            <style>
              body {
                font-family: 'Microsoft YaHei', 'SimSun', sans-serif;
                padding: 20px;
              }
              table {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 20px;
              }
              table, th, td {
                border: 1px solid #ddd;
              }
              th, td {
                padding: 8px;
                text-align: center;
              }
              th {
                background-color: #f2f2f2;
              }
              .header {
                text-align: center;
                margin-bottom: 20px;
              }
              .info {
                margin-bottom: 20px;
              }
              .total {
                text-align: right;
                margin-top: 12px;
                font-weight: bold;
              }
            </style>
          </head>
          <body>
            <div class="header">
              <h2>${this.title}</h2>
            </div>
            <div class="info">
              <p><strong>采购单号：</strong>${this.purchaseOrder.purchaseNo}</p>
              <p><strong>退换货单号：</strong>${this.currentReturnExchangeNo}</p>
            </div>
            <table>
              <thead>
                <tr>
                  <th>序号</th>
                  <th>物料编码</th>
                  <th>物料名称</th>
                  <th>规格型号</th>
                  <th>数量</th>
                  <th>单位</th>
                  <th>单价</th>
                  <th>金额</th>
                  <th>原因</th>
                </tr>
              </thead>
              <tbody>
                ${this.returnExchangeList.map((item, index) => `
                  <tr>
                    <td>${index + 1}</td>
                    <td>${item.materialCode || '-'}</td>
                    <td>${item.materialName || '-'}</td>
                    <td>${item.specification || '-'}</td>
                    <td>${item.quantity || 0}</td>
                    <td>${item.unit || '-'}</td>
                    <td>¥${item.unitPrice ? parseFloat(item.unitPrice).toFixed(2) : '0.00'}</td>
                    <td>¥${item.totalAmount ? parseFloat(item.totalAmount).toFixed(2) : '0.00'}</td>
                    <td>${item.reason || '-'}</td>
                  </tr>
                `).join('')}
              </tbody>
            </table>
            <div class="total">
              <p>总数量: ${this.totalQuantity}</p>
              <p>总金额: ¥${this.totalAmount.toFixed(2)}</p>
            </div>
          </body>
        </html>
      `;
      
      // 创建一个隐藏的iframe来渲染内容
      const iframe = document.createElement('iframe');
      iframe.style.visibility = 'hidden';
      iframe.style.position = 'fixed';
      iframe.style.right = '0';
      iframe.style.bottom = '0';
      iframe.style.width = '1024px';
      iframe.style.height = '768px';
      document.body.appendChild(iframe);
      
      iframe.contentWindow.document.open();
      iframe.contentWindow.document.write(content);
      iframe.contentWindow.document.close();
      
      // 等待内容加载完成
      setTimeout(() => {
        // 使用html2canvas将iframe内容转为图像
        html2canvas(iframe.contentWindow.document.body, {
          scale: 2,
          logging: false,
          useCORS: true
        }).then(canvas => {
          document.body.removeChild(iframe);
          
          const imgData = canvas.toDataURL('image/jpeg', 1.0);
          const pdf = new jsPDF('p', 'mm', 'a4');
          const pageWidth = pdf.internal.pageSize.getWidth();
          const pageHeight = pdf.internal.pageSize.getHeight();
          const imgWidth = pageWidth - 20;
          const imgHeight = (canvas.height * imgWidth) / canvas.width;
          
          let heightLeft = imgHeight;
          let position = 10;
          pdf.addImage(imgData, 'JPEG', 10, position, imgWidth, imgHeight);
          heightLeft -= pageHeight - 20;
          
          // 如果内容超过一页，继续添加页面
          while (heightLeft > 0) {
            position = heightLeft - imgHeight + 10;
            pdf.addPage();
            pdf.addImage(imgData, 'JPEG', 10, position, imgWidth, imgHeight);
            heightLeft -= pageHeight - 20;
          }
          
          // 保存文件
          pdf.save(fileName);
          this.$message.destroy();
          this.$message.success('PDF导出成功');
        }).catch(error => {
          document.body.removeChild(iframe);
          this.$message.destroy();
          this.$message.error('PDF导出失败：' + error);
        });
      }, 1000);
    },
    // 图片相关方法
    getImageUrl(text) {
      if (!text) return '';
      try {
        return getFileAccessHttpUrl(text);
      } catch (error) {
        console.error('获取文件URL失败:', error);
        return '';
      }
    },
    handlePreviewImage(text) {
      this.previewImage = this.getImageUrl(text);
      this.previewVisible = true;
    },
    handleImageError(e) {
      e.target.src = '';
      e.target.alt = '图片加载失败';
    }
  }
}
</script>

<style scoped>
.material-thumbnail-container {
  width: 80px;
  height: 60px;
  margin: 0 auto;
  overflow: hidden;
}

.material-thumbnail {
  max-width: 80px;
  max-height: 60px;
  cursor: pointer;
  object-fit: contain;
}
</style> 